package com.wondream.myframework.app.common.util;

import java.io.*;

public class ObjectTranscoder {
    public static byte[] serialize(Object value) throws IOException {
        if(value==null){
            return null;
        }
        byte[] result = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream os = null;
        try {
            bos = new ByteArrayOutputStream();
            os = new ObjectOutputStream(bos);
            os.writeObject(value);
            result = bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(os, bos);
        }
        return result;
    }

    public static Object deserialize(byte[] in) throws Exception {
        if(in == null && in.length==0){
            return null;
        }
        Object result = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;
        try {
            bis = new ByteArrayInputStream(in);
            is = new ObjectInputStream(bis);
            result = is.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(is, bis);
        }
        return result;
    }

    private static void close(Closeable... closeables) {
        for (Closeable closeable : closeables) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
